package com.deep.spring.v11.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import static com.deep.spring.v11.config.DataSourceType.MASTER;
import static com.deep.spring.v11.config.DataSourceType.SLAVE;

@Aspect
@Component
@Slf4j
@Order(1)
public class DynamicDataSourceAspect {

    @Pointcut("execution(public * com.deep.spring.v17.dynamic.service.*.*(..))")
    public void dynamicExecution() {
    }

    @Pointcut("@annotation(com.deep.spring.v17.dynamic.config.MasterSlave)")
    public void dynamicAnnotation() {
    }

    @Before("dynamicAnnotation()&&dynamicExecution()&&@annotation(masterSlave)")
    public void putDataSource(JoinPoint point, MasterSlave masterSlave) {
        DataSourceType value = masterSlave.value();
        if (MASTER.equals(value)) {
            DataSourceHolder.putDataSourceType(MASTER);
        } else if (SLAVE.equals(value)) {
            DataSourceHolder.putDataSourceType(SLAVE);
        } else {
            DataSourceHolder.putDataSourceType(SLAVE);
        }
        log.info("put datasource into current thread successfully");
    }

    @After("dynamicAnnotation()&&dynamicExecution()&&@annotation(masterSlave)")
    public void clearDataSource(JoinPoint point, MasterSlave masterSlave) {
        DataSourceHolder.clearDataSourceType();
        log.info("remove datasource from current thread successfully");
    }
}